import { BetaSchemaForm, ProFormInstance } from '@/components/Pro';
import { sysTenantControllerEdit } from '@/services/ess/sysTenant';
import {
  sysUserControllerGetUserRealPhone,
  sysUserControllerResetPassword,
  sysUserControllerThaw,
} from '@/services/ess/sysUser';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { message, Modal, Space } from 'antd';
import React, { useRef, useState } from 'react';
import { useIntl } from 'umi';

interface IProps {
  isEdit: boolean;
  formProps: API.SysTenant;
  handleEdit: (data: any) => void;
  relieveFreeze: (data: any) => void;
}

interface modelFormInterface {
  manId: string;
  manName: string;
  manState: string;
  manTel: string;
  remark: string;
  tenState: boolean;
  tenantName: string;
  tenantNo: string;
  validity: string[];
}

const EditModal: React.FC<IProps> = (props: IProps) => {
  const { confirm } = Modal;
  const intl = useIntl();
  const { isEdit, formProps, handleEdit, relieveFreeze } = props;
  const title = isEdit
    ? intl.formatMessage({ id: 'systemManagement.generalProcedure.edit' })
    : intl.formatMessage({ id: 'systemManagement.generalProcedure.view' });
  const formRef = useRef<ProFormInstance>();
  const [freezeStatus, setFreezeStatus] = useState(false);
  const [messageApi, contextHolder] = message.useMessage();
  const columns = [
    {
      title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.tenantInformation' }),
      valueType: 'group',
      colProps: { md: 24 },
      key: 'group_info',
      columns: [
        {
          title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.tenantCode' }),
          key: 'tenantNo',
          dataIndex: 'tenantNo',
          fieldProps: {
            maxLength: 10,
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: intl.formatMessage({ id: 'systemManagement.requiredFields.tenantCode' }),
              },
            ],
          },
        },
        {
          title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.tenantName' }),
          key: 'tenantName',
          dataIndex: 'tenantName',
          fieldProps: {
            maxLength: 30,
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: intl.formatMessage({ id: 'systemManagement.requiredFields.tenantName' }),
              },
            ],
          },
        },
        {
          title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.status' }),
          key: 'tenState',
          dataIndex: 'tenState',
          valueType: 'select',
          initialValue: true,
          valueEnum: new Map([
            [true, intl.formatMessage({ id: 'systemManagement.generalProcedure.enable' })],
            [false, intl.formatMessage({ id: 'systemManagement.generalProcedure.disable' })],
          ]),
          formItemProps: {
            rules: [
              {
                required: true,
                message: intl.formatMessage({ id: 'systemManagement.requiredFields.selectStatus' }),
              },
            ],
          },
        },
        {
          title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.termOfValidity' }),
          key: 'validity',
          dataIndex: 'validity',
          valueType: 'dateRange',
          formItemProps: {
            rules: [
              {
                required: true,
                message: intl.formatMessage({
                  id: 'systemManagement.requiredFields.validityPeriod',
                }),
              },
            ],
          },
        },
        {
          title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.remarks' }),
          key: 'remark',
          colProps: { md: 24 },
          dataIndex: 'remark',
          valueType: 'textarea',
          fieldProps: {
            placeholder: intl.formatMessage({
              id: 'systemManagement.tenantManagementMenu.noMoreThan140Words',
            }),
            maxLength: 140,
          },
        },
      ],
    },
    {
      title: intl.formatMessage({
        id: 'systemManagement.tenantManagementMenu.administratorInformation',
      }),
      valueType: 'group',
      colProps: { md: 24 },
      key: 'man_info',
      columns: [
        {
          title: intl.formatMessage({
            id: 'systemManagement.tenantManagementMenu.administratorUsername',
          }),
          key: 'manId',
          dataIndex: 'manId',
          fieldProps: {
            maxLength: 15,
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: intl.formatMessage({
                  id: 'systemManagement.requiredFields.adminUsername',
                }),
              },
              {
                pattern: new RegExp(/^[^\u4e00-\u9fa5]+$/, 'g'),
                message: intl.formatMessage({
                  id: 'systemManagement.requiredFields.noChineseCharacters',
                }),
              },
            ],
          },
        },
        {
          title: intl.formatMessage({
            id: 'systemManagement.tenantManagementMenu.administratorName',
          }),
          key: 'manName',
          dataIndex: 'manName',
          fieldProps: {
            maxLength: 30,
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: intl.formatMessage({ id: 'systemManagement.requiredFields.adminName' }),
              },
            ],
          },
        },
        {
          title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.status' }),
          key: 'manState',
          dataIndex: 'manState',
          valueType: 'select',
          request: () => fetchDictInfo(DATABASE_TYPE_ENUM.USER_STATUS),
          formItemProps: {
            rules: [
              {
                required: true,
                message: intl.formatMessage({ id: 'systemManagement.requiredFields.selectStatus' }),
              },
            ],
          },
        },
        {
          title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.contactNumber' }),
          key: 'manTel',
          dataIndex: 'manTel',

          formItemProps: {
            rules: [
              {
                required: true,
                message: intl.formatMessage({
                  id: 'systemManagement.requiredFields.contactNumber',
                }),
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: intl.formatMessage({
                  id: 'systemManagement.requiredFields.validMobileNumber',
                }),
              },
            ],
          },
        },
        {
          title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.frozenState' }),
          key: 'lockStatus',
          dataIndex: 'lockStatus',
          renderFormItem: () => {
            return (
              <div>
                <Space>
                  {freezeStatus ? (
                    <a
                      onClick={() => {
                        confirm({
                          title: intl.formatMessage({
                            id: 'systemManagement.supplementary.prompt',
                          }),
                          content: intl.formatMessage({
                            id: 'systemManagement.neddTochange.cancelFreeze',
                          }),
                          onOk() {
                            sysUserControllerThaw({ userId: formProps?.userId }).then((res) => {
                              if (res.success) {
                                message.success(
                                  intl.formatMessage({
                                    id: 'systemManagement.neddTochange.unfreezeSuccess',
                                  }),
                                );
                                setFreezeStatus(false);
                                relieveFreeze(true);
                              }
                            });
                          },
                        });
                      }}
                    >
                      {intl.formatMessage({ id: 'systemManagement.generalProcedure.unfreeze' })}
                    </a>
                  ) : (
                    <span>
                      {intl.formatMessage({ id: 'systemManagement.generalProcedure.normal' })}
                    </span>
                  )}
                  {isEdit && (
                    <a
                      onClick={() => {
                        confirm({
                          title: intl.formatMessage({
                            id: 'systemManagement.requiredFields.resetPassword',
                          }),
                          content: intl.formatMessage({
                            id: 'systemManagement.requiredFields.confirmResetPassword',
                          }),
                          onOk() {
                            const userId = formProps.manager?.userId;
                            sysUserControllerResetPassword({ userId: userId }).then((res) => {
                              if (res.success) {
                                Modal.info({
                                  title: intl.formatMessage({
                                    id: 'systemManagement.requiredFields.passwordResetSuccess',
                                  }),
                                  content: `${intl.formatMessage({
                                    id: 'systemManagement.requiredFields.newPassword',
                                  })}${res.data}`,
                                });
                              }
                            });
                          },
                        });
                      }}
                    >
                      {intl.formatMessage({
                        id: 'systemManagement.generalProcedure.resetPassword',
                      })}
                    </a>
                  )}
                </Space>
              </div>
            );
          },
        },
      ],
    },
  ];
  const openModalForm = (value) => {
    if (value) {
      sysUserControllerGetUserRealPhone({ userId: formProps.manager?.userId }).then((res) => {
        const formData = JSON.parse(JSON.stringify(formProps));
        setFreezeStatus(formData.freeze);
        formRef?.current?.setFieldsValue({ ...formData });
        if (res.success) {
          formRef?.current?.setFieldsValue({
            manTel: res.data,
          });
        }
      });
    }
  };
  const isOpenModal = false;
  return (
    <div>
      {contextHolder}
      <BetaSchemaForm
        modalProps={{
          destroyOnClose: true,
        }}
        formRef={formRef}
        title={title}
        layoutType="ModalForm"
        layout="horizontal"
        colProps={{ md: 12 }}
        style={{
          marginRight: 50,
        }}
        disabled={!isEdit}
        grid={true}
        labelCol={{
          flex: `0 0 120px`,
        }}
        submitter={isEdit}
        onOpenChange={openModalForm}
        open={isOpenModal}
        trigger={<a>{title}</a>}
        columns={columns}
        onFinish={async (values: modelFormInterface) => {
          const params: API.SysTenant = {
            // 租户信息
            tenantId: formProps.tenantId,
            tenantNo: values.tenantNo,
            tenantName: values.tenantName,
            startTime: values.validity[0],
            expireTime: values.validity[1],
            status: values.tenState,
            remark: values.remark,
            // 管理员信息
            manager: {
              userId: formProps.manager?.userId,
              userName: values.manId,
              nickName: values.manName,
              status: values.manState,
              phone: values.manTel,
            },
          };
          const res = await sysTenantControllerEdit(params);
          if (res.success) {
            messageApi.open({
              type: 'success',
              content: res.message,
            });
            handleEdit(true);
            return true;
          }
        }}
      />
    </div>
  );
};

export default EditModal;
